package com.hbnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbnu.pojo.Orders;
import com.hbnu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 当前用户订单分页 + 搜索
     */
    @GetMapping("/page")
    public Map<String, Object> getOrderPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam Integer userId,
            @RequestParam(required = false) String keyword
    ) {
        Page<Orders> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId);

        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(Orders::getOrderName, keyword);
        }

        IPage<Orders> result = orderService.getOrderPage(page, wrapper);

        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("data", result);
        return res;
    }

    /**
     * 查询当前用户所有订单
     */
    @GetMapping("/list")
    public Map<String, Object> getOrderList(@RequestParam Integer userId) {
        List<Orders> orders = orderService.getOrderByUserId(userId);
        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("data", orders);
        return res;
    }

    /**
     * 查询所有订单（管理员用）
     */
    @GetMapping("/listAll")
    public Map<String, Object> getOrderListAll() {
        List<Orders> orders = orderService.getOrderByAll();
        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("data", orders);
        return res;
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteOrder(@PathVariable Integer id) {
        boolean success = orderService.deleteOrder(id);
        Map<String, Object> res = new HashMap<>();
        res.put("success", success);
        res.put("message", success ? "删除成功" : "删除失败");
        return res;
    }

    /**
     * 更新订单（用于切换状态或修改其他信息）
     */
    @PostMapping("/update")
    public Map<String, Object> updateOrder(@RequestBody Orders orders) {
        boolean success = orderService.updateOrder(orders);
        Map<String, Object> res = new HashMap<>();
        res.put("success", success);
        res.put("message", success ? "更新成功" : "更新失败");
        return res;
    }

    /**
     * 导出当前用户订单为 CSV
     */
    @GetMapping("/export")
    public void exportOrderCSV(HttpServletResponse response,
                               @RequestParam Integer userId,
                               @RequestParam(required = false) String keyword) throws IOException {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId);
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(Orders::getOrderName, keyword);
        }

        List<Orders> orders = orderService.list(wrapper);

        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=orders.csv");

        PrintWriter writer = response.getWriter();
        writer.println("订单ID,订单名称,开始时间,结束时间,宠物种类,金额,状态");

        for (Orders order : orders) {
            writer.printf("%d,%s,%s,%s,%s,%d,%s\n",
                    order.getId(),
                    order.getOrderName(),
                    order.getOrderStarttime(),
                    order.getOrderEndtime(),
                    order.getPetKind(),
                    order.getMoney(),
                    order.getStatus());
        }

        writer.flush();
        writer.close();
    }
}
